<template>
  <div class="policy-trace-container">
    <header class="header-bar">
      <h1>政策溯源</h1>
    </header>

    <div class="main-content">
      <!-- 时间轴区域 -->
      <section class="timeline-section" id="timelineContainer">
        <PolicyTimeLine :policies="filteredPolicies" @edit="openPolicyDetail" />
      </section>

      <!-- 右侧：详情 / 新增 / 筛选 -->
      <aside class="details-sidebar">
        <template v-if="activeTab === 'detail' && selectedPolicy">
          <div class="policy-detail-header">
            <h2>{{ selectedPolicy.title }}</h2>
            <button class="close-btn" @click="closeTab">✖</button>
          </div>
          <p><strong>发布日期：</strong>{{ selectedPolicy.date }}</p>
          <p><strong>级别：</strong>{{ selectedPolicy.level }}</p>
          <p><strong>相关度：</strong>{{ selectedPolicy.relevance }}</p>
          <p><strong>内容：</strong>{{ selectedPolicy.description }}</p>
          <button class="edit-btn" @click="editPolicy">编辑</button>
        </template>

        <template v-else-if="activeTab === 'form'">
          <PolicyForm
            :policy="editingPolicy"
            @save="handleSavePolicy"
            @delete="handleDeletePolicy"
            @close="closeTab"
          />
        </template>

        <template v-else>
          <button class="btn-add-policy" @click="openNewPolicyForm">➕ 新增政策</button>
          <FilterPanel v-model:filters="filters" />
          <ExportPanel :policies="filteredPolicies" exportAreaSelector="#timelineContainer" />
        </template>
      </aside>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'

import FilterPanel from '@/components/FilterPanel.vue'
import ExportPanel from '@/components/ExportPanel.vue'
import PolicyTimeLine from '@/components/PolicyTimeLine.vue'
import PolicyForm from '@/components/PolicyForm.vue'

const filters = ref({
  levels: [],
  keyword: '',
  relevanceMin: null,
  relevanceMax: null,
})

const route = useRoute()
const allPolicies = ref([])
const selectedPolicy = ref(null)
const editingPolicy = ref(null)
const activeTab = ref(null) // null | 'detail' | 'form'
const currentGroupId = ref(null)

// 加载政策组数据
function loadPolicyGroup(groupId) {
  const allGroups = JSON.parse(localStorage.getItem('policyGroupsData')) || []
  const group = allGroups.find(g => g.id === parseInt(groupId))
  
  if (group) {
    currentGroupId.value = group.id
    allPolicies.value = group.policies
  } else {
    // 如果没有找到组，使用默认示例数据
    allPolicies.value = [
      { id: 1, title: '默认政策1', date: '2022-01-01', level: '国家', relevance: 0.8, description: '默认政策内容' }
    ]
  }
}

// 保存当前政策组
function saveCurrentPolicyGroup() {
  if (!currentGroupId.value) return
  
  const allGroups = JSON.parse(localStorage.getItem('policyGroupsData')) || []
  const groupIndex = allGroups.findIndex(g => g.id === currentGroupId.value)
  
  if (groupIndex !== -1) {
    allGroups[groupIndex].policies = allPolicies.value
    localStorage.setItem('policyGroupsData', JSON.stringify(allGroups))
  }
}

// 监听路由变化
watch(() => route.query.groupId, (newId) => {
  if (newId) {
    loadPolicyGroup(newId)
  }
}, { immediate: true })

// 初始化示例数据（如果没有数据）
function initSampleData() {
  if (!localStorage.getItem('policyGroupsData')) {
    const sampleGroups = [
      {
        id: 1,
        title: "科技创新支持政策",
        description: "国家及地方关于科技创新的系列支持政策",
        policies: [
          { id: 101, title: "国家科技创新2030规划", date: "2022-03-15", level: "国家", relevance: 0.95, description: "国家层面科技创新长期规划..." },
          { id: 102, title: "XX省科技创新十条", date: "2022-07-20", level: "省级", relevance: 0.85, description: "省级科技创新支持政策..." }
        ]
      },
      {
        id: 2,
        title: "中小企业扶持政策",
        description: "各级政府对中小企业的扶持措施",
        policies: [
          { id: 201, title: "中小企业促进法", date: "2021-09-01", level: "国家", relevance: 0.92, description: "国家中小企业基本法律..." }
        ]
      }
    ]
    localStorage.setItem('policyGroupsData', JSON.stringify(sampleGroups))
  }
}

onMounted(() => {
  initSampleData()
})

const filteredPolicies = computed(() => {
  return allPolicies.value.filter((policy) => {
    const matchesLevel = filters.value.levels.length === 0 || filters.value.levels.includes(policy.level)
    const matchesKeyword = !filters.value.keyword || policy.title.includes(filters.value.keyword)
    const rel = policy.relevance ?? 0
    const matchesRelevance =
      (filters.value.relevanceMin == null || rel >= filters.value.relevanceMin) &&
      (filters.value.relevanceMax == null || rel <= filters.value.relevanceMax)

    return matchesLevel && matchesKeyword && matchesRelevance
  })
})

function openPolicyDetail(policy) {
  selectedPolicy.value = policy
  editingPolicy.value = null
  activeTab.value = 'detail'
}

function openNewPolicyForm() {
  selectedPolicy.value = null
  editingPolicy.value = null
  activeTab.value = 'form'
}

function editPolicy() {
  editingPolicy.value = { ...selectedPolicy.value }
  activeTab.value = 'form'
}

function handleSavePolicy(policy) {
  if (policy.id) {
    const idx = allPolicies.value.findIndex(p => p.id === policy.id)
    if (idx !== -1) {
      allPolicies.value[idx] = { ...policy }
    }
  } else {
    const maxId = allPolicies.value.reduce((max, p) => Math.max(max, p.id || 0), 0)
    policy.id = maxId + 1
    allPolicies.value.push(policy)
  }
  saveCurrentPolicyGroup()
  closeTab()
}

function handleDeletePolicy(id) {
  allPolicies.value = allPolicies.value.filter(p => p.id !== id)
  saveCurrentPolicyGroup()
  closeTab()
}

function closeTab() {
  selectedPolicy.value = null
  editingPolicy.value = null
  activeTab.value = null
}
</script>

<style scoped>
.policy-trace-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--gradient-primary);
  color: var(--color-textPrimary);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header-bar {
  flex-shrink: 0;
  background: var(--color-navBg);
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 6px var(--color-shadow);
}

.header-bar h1 {
  margin: 0;
  font-weight: 700;
  font-size: 1.8rem;
}

.main-content {
  flex: 1;
  padding: 20px;
  display: flex;
  overflow: hidden;
}

.timeline-section {
  flex: 1;
  padding: 0 0 0 20px;
  overflow-x: auto;
  overflow-y: hidden;
  position: relative;
  background-color: var(--color-bgLight);
}

.details-sidebar {
  width: 360px;
  background: var(--color-surface);
  border-left: 1px solid var(--color-divider);
  padding: 20px;
  box-sizing: border-box;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.policy-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.policy-detail-header h2 {
  margin: 0;
  font-size: 1.4rem;
}

.close-btn {
  background: transparent;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
}

.edit-btn {
  background: var(--color-accent);
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  margin-top: 12px;
}

.btn-add-policy {
  background: var(--color-success);
  border: none;
  color: white;
  padding: 12px 16px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.3s;
}

.btn-add-policy:hover {
  background: #16a34a;
}
</style>
